<template>
  <div v-loading="pageLoading" style="width: 100%; height: 100%">
    <a-button
      type="primary"
      @click="showDialog"
      class="common-btn"
      v-if="canPublish"
      >发布文章</a-button
    >
    <div
      v-for="(item, index) in listData"
      class="article-list-div"
      :key="index"
      style="border-bottom: 1px solid #ededed"
    >
      <el-row type="flex">
        <el-col>
          <div class="article-list-title" @click="goDetail(item.id)">
            {{ item.title }}
          </div>
          <div
            class="article-list-content"
            v-show="item.content"
            v-html="item.content.replace('img', 'img style=display:none')"
          ></div>
          <div>
            <el-row type="flex" justify="space-between">
              <el-col :span="9">
                <span class="authorName-span">{{ item.authorName }}</span>
                <span>发布于 {{ item.createTime }}</span>
              </el-col>
              <el-col :span="8" class="rh">
                <span
                  v-for="(i, index) in item.actions"
                  :key="index"
                  class="class_article"
                >
                  <span
                    class="article-list-icon"
                    :key="index"
                    v-if="i.isShow"
                    @click="
                      handleOperation(
                        i.type,
                        item.id,
                        item.loginIfZan,
                        item.recommendFlag
                      )
                    "
                  >
                    <a-icon
                      :theme="i.theme"
                      :type="i.type"
                      :style="{ marginRight: '4px', color: i.color }"
                    />
                    {{ i.text }}
                  </span>
                </span>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      class="article-dialog"
      title="发布文章"
      :visible.sync="visible"
      center
      :show-close="false"
      width="800px"
      @close="close('form')"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="文章类型" prop="typeId">
          <el-select v-model="typeId" placeholder="选择文章类型" clearable>
            <el-option
              v-for="item in articletypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章">
          <quillEditor
            class="quillEditor"
            ref="quillEditor"
            :information="information"
            @handleRichtextAddClick="handleRichtextAddClick"
          ></quillEditor>
          <!-- <quill-editor
            style="height: 450px"
            v-model="form.content"
            ref="myQuillEditor"
            :options="editorOption"
          ></quill-editor> -->
        </el-form-item>
        <el-form-item label="上传文件" style="margin-top: 100px">
          <el-upload
            ref="upload"
            :headers="headers"
            action="/api/upload/uploadFile/9"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('form')">取 消</el-button>
        <el-button type="primary" @click="sure" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-pagination
      v-if="listData.length > 0"
      class="rh mr"
      background
      @size-change="handleSizeChange"
      @current-change="handleChangePage"
      :current-page="pn"
      :page-sizes="[5, 10, 15, 20, 30, 40]"
      :page-size="ps"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
import {
  getArticleList,
  addArticle,
  updateRecommendFlag,
  likeArticle,
} from "@/service/Api";
import quillEditor from "@/components/quillEditor/quillEditor";
export default {
  name: "articleList",
  props: ["moduleId", "menuList"],
  components: {
    quillEditor,
  },
  data() {
    return {
      information: "请输入文章的内容~",
      headers: {
        "API-User-Token": sessionStorage.getItem("token"), //文件上传需携带token
      },
      visible: false,
      loading: false,
      pageLoading: false,
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 14,
      },
      typeId: undefined,
      pn: 1,
      ps: 5,
      total: 0,
      listData: [],
      form: {
        title: "",
        content: "",
        path: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { required: true, message: "请输入标题", trigger: "change" },
          { min: 3, max: 100, message: "长度应该是3到100", trigger: "blur" },
          { min: 3, max: 100, message: "长度应该是3到100", trigger: "change" },
        ],
      },
      fileList: [],
      annexTitle: [], //string附件名，多个之间用","隔开
      annexPath: [], //string	附件路径，多个之间用","隔开
      articleId: 0,
      canPublish: false,
      uploading: "api/upload/uploadFile/6",
      loginIfZan: 0,
      editorOption: {
        theme: "snow",
        placeholder: "请输入文本...",
      },
      fileName: [],
      articletypeList: [],
    };
  },
  watch: {
    moduleId: {
      handler(n, o) {
        // n为1时处于公司规划的状态，n为5为热点技术
        this.menuFlag = n;
        this.pn = 1;
        this.fileList = [];
        if (this.menuFlag !== 1) {
          //初始化界面
          var items = this.menuList[0].children;
          if (this.canPublish) {
            // 能发布文章的类型处理
            this.articletypeList = items.filter(function (item) {
              return item.name;
            });
          } else {
            this.articletypeList = items.filter(function (item) {
              return !item.name.match(/公司规划/);
            });
          }
        }
        this.getArticleList();
      },
      immediate: true,
    },
  },
  created() {
    this.init();
  },
  methods: {
    showDialog() {
      this.fileList = [];
      this.typeId = Number(this.moduleId);
      this.visible = true;
    },
    init() {
      getArticleList({
        pn: this.pn,
        ps: this.ps,
        moduleId: 1,
      }).then((res) => {
        if (res.code == 0) {
          // console.log("2345", res.data.canPublish);
          var items = this.menuList[0].children;
          if (res.data.canPublish) {
            this.articletypeList = items.filter(function (item) {
              return item.name;
            });
          } else {
            this.articletypeList = items.filter(function (item) {
              return !item.name.match(/公司规划/);
            });
          }
        }
      });
    },
    close(formName) {
      this.$refs[formName].resetFields();
      this.form.content = "";
      this.fileList = [];
      this.$refs.upload.clearFiles();
      this.visible = false;
    },
    sure() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          let annexTitle = "";
          let annexPath = "";
          this.fileList.forEach((item) => {
            annexTitle += item.name + ",";
            annexPath += item.response.data.fileIds + ",";
          });
          setTimeout(() => {
            addArticle({
              moduleId: this.typeId,
              title: this.form.title,
              content: this.form.content,
              annexTitle: annexTitle,
              annexPath: annexPath,
            }).then((res) => {
              if (res.data == 0) {
                this.loading = false;
                this.visible = false;
                this.$refs.quillEditor.text = "";
                this.getArticleList();
              }
            });
          }, 2000);
        } else {
          this.$message.info("请检查填写的信息");
          return false;
        }
      });
    },
    handleRichtextAddClick(val) {
      this.form.content = val;
    },
    handleCancel(formName) {
      this.$refs[formName].resetFields();
      this.visible = false;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleSuccess(res, file, fileList) {
      if (res.code === 0) {
        // console.log("图片上传成功", res, "file", file, "fileList", fileList);
        this.$message.success("上传成功");
        // this.annexPath.push(res.data.fileIds);
        // this.annexTitle.push(file.name);
        // this.fileList.push();
      }
    },
    goDetail(id) {
      this.$router.push({
        path: "/exchange/articleListDetail",
        query: {
          menuFlag: this.menuFlag,
          id: id,
        },
      });
    },
    getArticleList() {
      this.pageLoading = true;
      getArticleList({
        pn: this.pn,
        ps: this.ps,
        moduleId: Number(this.menuFlag),
      })
        .then((res) => {
          // console.log(res.data.canPublish, "aa");
          this.records = res.data.records;
          this.total = res.data.total;
          this.canPublish = res.data.canPublish;
          if (this.records.length > 0) {
            this.listData = this.records.map((item) => {
              this.articleId = item.id;
              this.loginIfZan = item.loginIfZan;
              if (item.annexTitle && item.annexPath) {
                this.fileList.push({
                  name: item.annexTitle,
                  url: item.annexPath,
                });
              }
              return {
                ...item,
                actions: [
                  {
                    type: "vertical-align-top",
                    text: "推荐到首页",
                    isShow: item.recommendFlag == 2 || !item.recommendFlag,
                  },
                  {
                    type: "vertical-align-top",
                    text: "取消推荐",
                    isShow: item.recommendFlag == 1,
                  },
                  {
                    type: "like-o",
                    text: item.zanCount ? item.zanCount : 0,
                    isShow: true,
                    color: item.loginIfZan == 0 ? "#00B98D" : "#8C8C8C",
                    theme: item.loginIfZan == 0 ? "filled" : "outlined",
                  },
                  {
                    type: "eye",
                    text: item.browseCount ? item.browseCount : 0,
                    isShow: true,
                    color: "#8C8C8C",
                  },
                  {
                    type: "message",
                    text: item.commentCount ? item.commentCount : 0,
                    isShow: true,
                    color: "#8C8C8C",
                  },
                ],
              };
            });
            // console.log(123, this.fileList);
            this.pageLoading = false;
          } else {
            this.listData = [];
            this.pageLoading = false;
          }
        })
        .catch((_) => {
          this.pageLoading = false;
        });
    },
    handleChangePage(val) {
      this.pn = val;
      this.getArticleList();
    },
    handleSizeChange(val) {
      this.ps = val;
      this.getArticleList();
    },
    handleOperation(type, id, loginIfZan, recommendFlag) {
      let flag = "";
      if (recommendFlag == 2 || !recommendFlag) {
        flag = 1;
      } else {
        flag = 2;
      }
      if (!flag) {
        return;
      }
      if (type == "vertical-align-top") {
        updateRecommendFlag({ id, flag }).then((res) => {
          this.getArticleList();
          this.$message.success("操作成功！");
        });
      } else if (type == "like-o") {
        likeArticle(id).then((res) => {
          console.log(res);
          if (loginIfZan == 0) {
            this.$message.info("已取消点赞！");
          } else {
            this.$message.success("点赞成功！");
          }
          this.getArticleList();
        });
      } else if (type == "message") {
        this.goDetail(id);
      }
    },
  },
};
</script>

<style scoped>
@import "../../../../styles/common.css";
/* @import '../../../../styles/zh-quill.css'; */

.list-mr {
  margin-top: 15px;
}

.common-btn {
  width: 120px;
  font-size: 14px;
  background-color: #00b98d;
  border-color: #00b98d;
}

.upload-btn:hover,
.upload-btn:focus {
  border-color: #00b98d;
  color: #00b98d;
}

.article-list-div {
  margin-top: 10px;
}

.article-list-div .article-list-title {
  font-size: 20px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(48, 49, 51, 1);
}

.article-list-div .article-list-title:hover {
  cursor: pointer;
  color: #00b98d;
}

.article-list-div .article-list-content {
  margin: 10px 0 10px 0;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: rgba(96, 98, 102, 1);
  height: 24px;
  line-height: 24px;
  text-overflow: ellipsis;
  /* white-space: nowrap; */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  cursor: pointer;
}
.article-list-div .article-list-icon {
  display: inline-block;
  width: 52px;
  text-align: center;
  cursor: pointer;
}

.rh .class_article:first-child .article-list-icon:first-child {
  width: 120px;
}
.rh .class_article:nth-child(2) .article-list-icon:first-child {
  width: 120px;
}
.authorName-span {
  margin-right: 20px;
}
</style>